<template>
  <div class="order-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :maxNum="6" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="refresh">
        <template #headerRight>
          <a-popover content="导出库存">
            <a-button type="text" style="font-size: 16px; color: #141840">
              <template #icon>
                <icon-download />
              </template>
            </a-button>
          </a-popover>
        </template>
        <template #headerLeft>
          <a-button style="margin-right: 10px" class="gray-outline" :loading="matchLoading" @click="updateSacles" v-if="$authPass('oms.order.fba.syncProductRelated')">更新SKU及销售员</a-button>
          <a-button style="margin-right: 10px" class="gray-outline" @click="setTag('mul')">设置标签</a-button>
          <a-button style="margin-right: 10px" class="gray-outline" :loading="asyncLoading" @click="asyncOrder">一键同步订单</a-button>
          <a-button style="margin-right: 10px" type="text" @click="copy">一键复制订单号</a-button>
        </template>
        <template #tableBody>
          <a-table size="mini" class="table-two-line" v-model:selected-keys="ids" :data="dataList" @cell-mouse-leave="leaveCell" @cell-mouse-enter="enterCell" @sorter-change="sortChange" row-key="id" :loading="loading" :row-selection="rowSelection" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column title="店铺" #cell="{ record, rowIndex }" :width="120">
                <div>{{ record.shopName }}</div>
                <div style="margin: 5px 0">
                  <a-tag color="arcoblue" size="small" bordered v-if="filterStatus(record.status) != '已取消'">{{ filterStatus(record.status) }}</a-tag>
                  <a-tag color="arcoblue" size="small" bordered v-else>{{ filterStatus(record.status) }}</a-tag>
                </div>
                <!-- <TextLimit position="top" :rows="1">{{ record.shopName }}</TextLimit> -->
              </a-table-column>
              <a-table-column :width="120">
                <template #title>
                  <div>平台单号</div>
                  <div>商家订单号</div>
                </template>
                <template #cell="{ record, rowIndex }">
                  <TextLimit style="width: 100px" class="highlight" position="top" :rows="1">{{ record.platformOrderNumber ? record.platformOrderNumber : '--' }}</TextLimit>
                  <TextLimit style="width: 100px" class="highlight" position="top" :rows="1">{{ record.merchantOrderNumber ? record.merchantOrderNumber : '--' }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column title="国家" #cell="{ record, rowIndex }" :width="120">
                <div>{{ $extract(record, 'address.countryName') }}({{ $extract(record, 'address.countryCode') }}) </div>
                <!-- <div>{{ $extract(record, 'address.countryCode') }} </div> -->
              </a-table-column>
              <a-table-column title="省州(邮编)" #cell="{ record, rowIndex }" :width="120">
                <span>{{ $extract(record, 'address.stateOrRegion') }}({{ $extract(record, 'address.postalCode') }})</span>
              </a-table-column>
              <a-table-column title="承运商/跟踪号" #cell="{ record, rowIndex }" :width="120">
                <TextLimit style="width: 100px" position="top" :rows="1">{{ filterPackage(record).carrier }}</TextLimit>
                <TextLimit style="width: 100px" position="top" :rows="1">{{ filterPackage(record).trackingNumber }}</TextLimit>
              </a-table-column>
              <a-table-column title="下单时间（+8）" data-index="gmtPurchase" :sortable="{ sortDirections: ['ascend', 'descend'] }" #cell="{ record, rowIndex }" :width="140">
                <span>{{ $setTime(record.gmtPurchase) }}</span>
              </a-table-column>
              <a-table-column title="实际发货时间" data-index="gmtShip" :sortable="{ sortDirections: ['ascend', 'descend'] }" #cell="{ record, rowIndex }" :width="140">
                <span>{{ $setTime(record.gmtShip) }}</span>
              </a-table-column>
              <a-table-column title="图片" #cell="{ record, rowIndex }" :width="80">
                <div class="item-detail picture" v-for="item in record.itemList">
                  <ImgPopover :src="item.productPic">
                    <template #con>
                      <a-image :preview="false" width="40" height="40" fit="contain" :src="item.productPic" />
                    </template>
                  </ImgPopover>
                </div>
              </a-table-column>
              <a-table-column title="商品名称" #cell="{ record, rowIndex }" :width="140">
                <div class="item-detail name" v-for="item in record.itemList">
                  <TextLimit position="top" :rows="2">{{ item.productName }}</TextLimit>
                </div>
              </a-table-column>
              <a-table-column title="ASIN/MSKU" #cell="{ record, rowIndex }" :width="120">
                <div :class="['item-detail', 'asin', record.itemList.length > 1 ? 'item-detail-line' : '']" v-for="item in record.itemList">
                  <div class="highlight">{{ item.asin ? item.asin : '--' }}</div>
                  <div class="highlight">{{ item.msku ? item.msku : '--' }}</div>
                </div>
              </a-table-column>
              <a-table-column title="SKU/类目" #cell="{ record, rowIndex }" :width="120">
                <div :class="['item-detail', 'category', record.itemList.length > 1 ? 'item-detail-line' : '']" v-for="item in record.itemList">
                  <ShowSpuDetailBySku :val="item.productSku" :showLimit="true" :rows="1" />
                  <div class="highlight">{{ item.productCategoryName ? item.productCategoryName : '--' }}</div>
                </div>
              </a-table-column>
              <a-table-column title="销售员" #cell="{ record, rowIndex }" :width="80">
                <div :class="['item-detail', 'user', record.itemList.length > 1 ? 'item-detail-line' : '']" v-for="item in record.itemList">
                  {{ item.salerName }}
                </div>
              </a-table-column>
              <a-table-column title="订购数量" #cell="{ record, rowIndex }" :width="80">
                <div :class="['item-detail', 'num', record.itemList.length > 1 ? 'item-detail-line' : '']" v-for="item in record.itemList">
                  {{ item.qtyOrdered }}
                </div>
              </a-table-column>
              <a-table-column title="售价/优惠" #cell="{ record, rowIndex }" :width="80">
                <div :class="['item-detail', 'price', record.itemList.length > 1 ? 'item-detail-line' : '']" v-for="item in record.itemList">
                  <div class="highlight" v-if="item.amtSell">${{ item.amtSell }}</div>
                  <div class="highlight" v-if="item.amtDiscount">${{ item.amtDiscount }}</div>
                </div>
              </a-table-column>
              <a-table-column title="标签" #cell="{ record, rowIndex }" :width="140">
                <div v-if="record.tagList" class="tag-con">
                  <a-tag size="small" :color="item.color" v-for="item of record.tagList" style="margin: 0 5px 5px 0; color: #2c4358">{{ item.name }}</a-tag>
                  <span @click="setTag('single', record)" style="font-size: 12px; color: rgb(var(--primary-6)); cursor: pointer" class="del-icon icon icon-bianji1"></span>
                </div>
              </a-table-column>
              <a-table-column title="操作" #cell="{ record, rowIndex }" :width="80" fixed="right">
                <a-button class="mr10" type="text" @click="toDetail(record)">详情</a-button>
                <a-button type="text" @click="showLogModal(record)">日志</a-button>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>

  <Tag ref="tag" :dataList="tagList" @save="saveTag" type="fba" />
  <CommonLogsDialog v-if="showLogDialog" api="listOrderLogs" :id="id" :isShow="showLogDialog" @closed="showLogDialog = false" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { useRouter } from 'vue-router'
  import { TabData } from '@arco-design/web-vue/es/tabs/interface'
  import { fbaOrder, addTagBatch, cancelTagBatch, matchingProduct, syncOrders, tagList, findShopMarketByParam } from '@/api/order'
  import { getShopMarketAll } from '@/api/base'
  import { findShopListByShare, findWarehouseListByParam } from '@/api/warehouse'
  import { getOrganizesUser } from '@/api/system'
  import { countriesOptions } from '@/utils/countries'
  import { Message } from '@arco-design/web-vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import Tag from '../../components/tag/tagList.vue'
  import TextLimit from '@/components/textLimit.vue'
  import { watch } from 'vue'
  import useClipboard from 'vue-clipboard3'
  import _ from 'lodash-es'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'

  export default defineComponent({
    components: {
      FilterTable,
      TableWrap,
      Tag,
      TextLimit,
      CommonLogsDialog,
    },
    props: ['status', 'getCountOrderStatus'],
    setup(props: any, { emit }) {
      const router = useRouter()
      const tag = ref()
      const { toClipboard } = useClipboard()
      const data: any = reactive({
        filterItem: [
          {
            key: 'marketplaceIdList',
            label: '站点',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'sellerMarketIdList',
            label: '店铺',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },

          {
            type: 'input_keyword',
            key: 'skuList',
            keyItems: [
              { label: 'SKU', value: 'skuList' },
              { label: 'MSKU', value: 'mskuList' },
              { label: '商品名称', value: 'productNameList' },
            ],
            keyWidth: 90,
            value: ref(),
            placeholder: '请输入',
            label: 'SKU',
            width: 160,
            isMultiple: true,
          },
          {
            type: 'input_keyword',
            key: 'platformOrderNumberList',
            keyItems: [
              { label: '平台单号', value: 'platformOrderNumberList' },
              { label: '商家订单号', value: 'merchantOrderNumberList' },
            ],
            keyWidth: 120,
            value: ref(),
            placeholder: '请输入',
            label: '平台单号',
            width: 160,
            isMultiple: true,
          },
          {
            key: 'tagIdList',
            label: '标签',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'salerIdList',
            label: '销售员',
            value: ref(),
            type: 'select',
            width: 140,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            type: 'keyword_date_range',
            key: 'gmtPurchase',
            keyItems: [
              { label: '下单时间(+8)', value: 'gmtPurchase' },
              { label: '下单时间(+0)', value: 'gmtPurchase0' },
              { label: '创建时间', value: 'gmtCreate' },
              // { label: '承诺发货时间', value: 'gmtLatestShip' },
              { label: '实际发货时间', value: 'gmtShip' },
              // { label: '标发货时间', value: 'gmtVirtualShip' },
            ],
            keyWidth: '110',
            value: ref(),
            placeholder: '请输入',
            label: '下单时间(+8)',
            width: 200,
          },
          {
            key: 'warehouseCodeList',
            label: '发货仓',
            value: ref(),
            type: 'input_search',
            width: '100%',
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            key: 'trackingNumber',
            label: '物流跟踪号',
            value: ref(),
            type: 'input_search',
            width: '100%',
          },
          {
            key: 'isCustom',
            label: '是否定制',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [
              { label: '是定制', value: true },
              { label: '否定制', value: false },
            ],
          },
          // {
          //   key: 'isTransparency',
          //   label: '是否透明计划',
          //   value: ref(),
          //   type: 'select',
          //   width: '100%',
          //   optionItems: [
          //     { label: '是透明计划', value: true },
          //     { label: '否透明计划', value: false },
          //   ],
          // },
          // {
          //   key: 'isVirtualShip',
          //   label: '虚假发货',
          //   value: ref(),
          //   type: 'select',
          //   width: '100%',
          //   optionItems: [
          //     { label: '是', value: true },
          //     { label: '否', value: false },
          //   ],
          // },
          {
            key: 'amtPay',
            label: '订单金额',
            value: ref(),
            type: 'input_search',
            width: '100%',
          },
          // {
          //   key: 'shipRemainDay',
          //   label: '发货剩余天数',
          //   value: ref(),
          //   type: 'input_search',
          //   width: '100%',
          // },
          {
            key: 'countryCodeList',
            label: '收货国家',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: countriesOptions.map((e: any) => {
              e.label = `${e.name}-${e.short}`
              e.value = e.short
              return e
            }),
            attrs: {
              'allow-search': true,
            },
          },
        ],
        columns: [
          { title: '店铺', dataIndex: 'name', width: '130px' },
          { title: '图片', dataIndex: 'name', width: '140px' },
          { title: '产品名称/SKU', dataIndex: 'name', width: '250px' },
          { title: 'MSKU/FNSKU', dataIndex: 'name', width: '250px' },
          { title: 'SPU/类目', dataIndex: 'name', width: '200px' },
          { title: '品牌', dataIndex: 'name', width: '110px' },
          // { title: '单位', dataIndex: 'name', width: 120 },
          { title: '产品类型', dataIndex: 'name', width: '110px' },
          { title: '数量', dataIndex: 'name', width: '140px' },
          { title: '库存属性', dataIndex: 'name', width: '140px' },
          { title: '单位成本', dataIndex: 'name', width: '120px' },
          { title: '货值', dataIndex: 'name', width: '80px' },
          { title: '上架货位', dataIndex: 'name', width: '120px' },
        ],
        dataList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        expandable: {},
        loading: false,
        isCollapse: false,
        info: {
          type: 'in',
          id: '',
        },
        id: '',
        searchValue: {},
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        tagList: [],
        ids: [],
        setsingleTagId: [],
        editTagFlag: 'mul',
        matchLoading: false,
        asyncLoading: false,
        showLogDialog: false,
      })
      const searchByVal = (info: any) => {
        let obj = _.cloneDeep(info)
        console.log(obj)
        data.searchValue = info
        if (data.searchValue.startDate) {
          data.searchValue.startDate = `${data.searchValue.startDate} 00:00:00`
          data.searchValue.endDate = `${data.searchValue.endDate} 23:59:59`
        }
        // for (const key in obj) {
        //   if (key == 'date' && obj[key]) {
        //     data.searchValue.startDate = `${obj[key][0]} 00:00:00`
        //     data.searchValue.endDate = `${obj[key][1]} 23:59:59`
        //   } else {
        //     data.searchValue[key] = obj[key]
        //   }
        // }
        data.pageNation.pageNum = 1
        props.getCountOrderStatus(data.searchValue)
        getList()
      }
      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const toDetail = (item: any) => {
        router.push({
          path: '/order/fbaOrder/components/fbaOrderDetail',
          query: {
            id: item.id,
          },
        })
      }

      const enterCell = (record: TabData) => {
        // console.log(record, '1')
      }
      const leaveCell = (record: TabData) => {
        // console.log(record, '2')
      }

      const getList = async () => {
        let params = {
          ...data.searchValue,
          status: props.status,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res = await fbaOrder(params)
        data.dataList = res?.data?.records
        data.pageNation.total = res?.data?.total

        data.dataList.map((e: any) => {
          let obj = countriesOptions.find((el) => e.address.country == el.name || e.address.country == el.en)
          e.address.countryName = obj?.name
          return e
        })
        data.loading = false
      }

      const setTag = (type: string, item: any) => {
        if (data.ids.length <= 0 && type == 'mul') {
          return Message.error('请选择需要操作的数据')
        }
        data.editTagFlag = type
        data.tagList = []
        data.setsingleTagId = []
        if (type == 'single') {
          data.setsingleTagId.push(item.id)
          data.tagList.push(...item.tagList)
        } else {
          data.ids.forEach((e: string) => {
            let obj: any = data.dataList.find((el: any) => e == el.id)
            if (obj) {
              data.tagList.push(...(obj?.tagList || []))
            }
          })
        }

        tag.value.visible = true
      }

      const saveTag = async (ids: Array<string>, type: string) => {
        let params = {
          orderIdList: data.editTagFlag == 'mul' ? data.ids : data.setsingleTagId,
          // tagIdList: ids,
          tagCodeList: ids,
        }

        let res: any = {}

        if (type == 'add') {
          res = await addTagBatch(params)
        } else {
          res = await cancelTagBatch(params)
        }

        if (res.code == 'SUCCESS') {
          type == 'add' ? Message.success('添加标签成功') : Message.success('删除标签成功')
          tag.value.visible = false
          data.ids = []
          tag.value.ids = []
          setTimeout(() => {
            getList()
          }, 1000)
        }
      }

      const updateSacles = async () => {
        if (data.ids.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        data.matchLoading = true
        const res: any = await matchingProduct(data.ids)
        if (res.code == 'SUCCESS') {
          Message.success('更新成功')
          data.ids = []
        }

        data.matchLoading = false
      }
      const asyncOrder = async () => {
        if (data.ids.length <= 0) {
          return Message.error('请选择需要操作的数据')
        }
        data.asyncLoading = true
        const res: any = await syncOrders(data.ids)
        if (res.code == 'SUCCESS') {
          Message.success('同步成功')
          data.ids = []
        }
        data.asyncLoading = false
      }

      const filterStatus = (num: number) => {
        let text = ''
        if (num >= -199 && num <= -100) {
          text = '已取消'
        } else if (num >= 100 && num <= 199) {
          text = ' 待支付'
        } else if (num >= 200 && num <= 299) {
          text = ' 待发货'
        } else if (num >= 600 && num <= 699) {
          text = ' 已发货'
        } else if (num >= 800 && num <= 899) {
          text = ' 已完成'
        }
        return text
      }

      const sortChange = (item: any, extra: any) => {
        if (extra) {
          data.searchValue.sortField = item
          data.searchValue.sortType = extra == 'ascend' ? '1' : '-1'
        } else {
          data.searchValue.sortField = ''
          data.searchValue.sortType = ''
        }
        getList()
      }

      const getMarketList = async () => {
        const res = await getShopMarketAll()
        let arr = res.data.map((e: any) => {
          e.label = e.marketplaceName
          e.value = e.marketplaceId
          return e
        })
        console.log(arr)

        data.filterItem[0].optionItems = arr
      }

      const getShopListByShare = async () => {
        const res = await findShopMarketByParam()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.shopName
          e.value = e.sellerMarketId
        })
        data.filterItem[1].optionItems = arr
      }

      const getTagList = async () => {
        const res = await tagList()
        let arr = res?.data
        data.filterItem[4].optionItems = arr.map((e: any) => {
          e.label = e.name
          // e.value = e.id
          e.value = e.code
          return e
        })
      }

      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let arr = res.data?.records
          arr.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.filterItem[5].optionItems = arr
        }
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.warehouseName
          e.value = e.warehouseCode
        })
        data.filterItem[7].optionItems = arr
      }

      const copy = async () => {
        let arr = data.dataList.map((e: any) => e.platformOrderNumber)
        try {
          // 复制
          await toClipboard(arr.join('\n'))
          Message.success('复制成功')
          // 复制成功
        } catch (e) {
          // 复制失败
        }
      }

      const filterPackage = (item: any) => {
        return item.packageList && item.packageList[0] ? item.packageList[0] : {}
      }

      const refresh = () => {
        sizeChange(20)
        props.getCountOrderStatus()
      }

      const showLogModal = (info: any) => {
        data.id = info.id
        data.showLogDialog = true
      }

      watch(
        () => props.status,
        () => {
          setTimeout(() => {
            sizeChange(20)
          }, 150)
        }
      )

      getMarketList()
      getShopListByShare()
      getWareHouseList()
      getUSerList()
      getTagList()
      getList()

      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        toDetail,
        tag,
        enterCell,
        leaveCell,
        setTag,
        saveTag,
        updateSacles,
        asyncOrder,
        filterStatus,
        sortChange,
        copy,
        filterPackage,
        refresh,
        showLogModal,
      }
    },
  })
</script>

<style lang="less" scoped>
  .order-con {
    height: calc(100vh - @menuAndTabHeight);
    width: 100%;

    :deep(.arco-table-cell-align-left) {
      padding: 0 !important;
    }

    .item-detail {
      min-height: 56px;
      // height
      width: 100%;
      padding: 6px 6px;
      box-sizing: border-box;
    }

    .item-detail-line {
      border-bottom: 1px solid #e5e6eb;
    }

    .tag-con {
      &:hover .del-icon {
        display: block;
      }
      .del-icon {
        display: none;
      }
    }
  }
</style>
